//app.js
App({
  host: 'https://wechat.neiyibaba.cn',
  state: 'weChatApp',
  onLaunch: function () {
    //调用API从本地缓存中获取数据
    var that = this

    wx.checkSession({
      success: function (a) {
        //session 未过期，并且在本生命周期一直有效
        console.log("登陆尚未过期:%o",a);
        wx.removeStorageSync("user");
        wx.removeStorageSync("token");
        that.userLogin();
      },
      fail: function () {
        //登录态过期 重新登录
        wx.removeStorageSync("user");
        wx.removeStorageSync("token");
        that.userLogin();
      }
    })
  },

  userLogin: function (callback) {
    var that = this
    var token = wx.getStorageSync('token')
    if (token) {
      callback()
    } else {
      wx.login({
        success: function (body) {
          console.log("wx_login response:%o", body);
          if (body.code) {
            wx.setStorageSync("code",body.code);

            wx.getSetting({
              success(res) {
                if (!res.authSetting['scope.userInfo']) {
                  wx.authorize({
                    scope: 'scope.userInfo',
                    success() {
                      // 用户已经同意小程序使用录音功能，后续调用 wx.startRecord 接口不会弹窗询问
                      wx.getUserInfo({
                        lang:"zh_CN",
                        success(res){
                          var userInfo = res.userInfo
                          var nickName = userInfo.nickName
                          var avatarUrl = userInfo.avatarUrl
                          var gender = userInfo.gender //性别 0：未知、1：男、2：女
                          var province = userInfo.province
                          var city = userInfo.city
                          var country = userInfo.country

                          wx.setStorageSync("user",{userLogo:avatarUrl,name:nickName});

                          var data = res.encryptedData;
                          var iv = res.iv;
                          console.log("授权用户信息获取:%o",res.userInfo);
                          console.log("cd:%o",data);
                          console.log("iv:%o",iv);
                        }
                      })
                    }
                  })
                }
              }
            })
            //1.从自己的服务器获取微信小程序配置信息
            //2.授权获取用户信息
            //3.缓存到本地
            that.postJson({
              url:'/wx/config/msapp',
              data:{code:body.code}
            },function(result,data){
              if(result=="0"){
                wx.getUserInfo({
                  success: function (loginInfo) {
                    wx.setStorageSync('userInfo', res.userInfo)
                    var param = {
                      'iv': loginInfo.iv,//wx.getUserInfo接口返回那里的iv
                      'rawData': loginInfo.rawData, //wx.getUserInfo接口返回那里的iv
                      'signature': loginInfo.signature,// wx.getUserInfo接口返回那里的signature
                      'encryptedData': loginInfo.encryptedData,  //wx.getUserInfo接口返回那里的encryptedData
                      'session_key': data.data.session_key //wx.login接口下面 “code 换取 session_key” 获得
                    }

                   that.postJson({
                     data:param,
                     url:'/user/login'
                   },function(res,loginResult){
                     if(res == "0"){
                       wx.showToast({
                         title: '登陆成功',
                         mask:true
                       })
                       wx.setStorageSync("user", loginResult);
                       wx.setStorageSync("token",loginResult.token);
                     }
                   })
                  },
                  fail: function (res) {
                    wx.showModal({
                      title: '警告',
                      showCancel: true,
                      cancelText: '不授权',
                      confirmText: '授权',
                      content: '若不授权微信登陆，将无法使用本应用；点击重新获取授权，则可重新使用；若点击不授权，后期还使用小程序，需在微信【发现】——【小程序】——删掉【大风名片】，重新搜索授权登陆，方可使用。',
                      success: function (res) {
                        if (res.confirm) {
                          wx.openSetting({
                            success: function (res) {
                              if (!res.authSetting["scope.userInfo"] || !res.authSetting["scope.userLocation"]) {
                                that.f('', function () {
                                  callback('')
                                })
                              }
                            }
                          })
                        } else if (res.cancel) {
                        }
                      }
                    })
                  }
                })
              }else{
              console.log("获取小程序登陆配置信息失败：%o",data);
              }
            })
          } else {
            console.log('登录失败')
          }
        }
      })
    }

  },
  
  refreshUserInfo: function (callback) {
    var url = '/user/info'
    this.postJson({
      url:url,
    },function(code,data){
      if(code==200){
        wx.setStorageSync("user", data);
      }else{
        console.error("刷新用户信息失败:%o",data);
      }
    })
  },
  postJson: function (data, callback) {
    var url = data.url.indexOf("http://") != -1 ? data.url : this.host + data.url;
    var token = wx.getStorageSync('token');
    if(!data.data){
      data.data={};
    }
    data.data["token"] = token;
    data.data["state"] = this.state;
    wx.request({
      url: url,
      method: 'POST',
      data: data.data,
      header: {
        'token': token,
        'content-type': 'application/json'
      },
      success: function (res) {
        var data = res.data;
        callback(data.result, data.result == "0" ? data.data : data.msg);
      },
      fail: function (res) {
        console.log('请求出错');
        wx.hideLoading()
      }
    })
  }
})